package service

import (
	"context"
	"fmt"
	"gitee.com/DonHz/basic-go/webook/internal/repository"
	"gitee.com/DonHz/basic-go/webook/internal/service/sms"
	"math/rand"
)

const codeTplId = "1877556"
var (
	ErrCodeSendTooMany = repository.ErrCodeSendTooMany
	ErrCodeVerifyTooMany = repository.ErrCodeVerifyTooMany
)

type CodeService interface{
	Send(ctx context.Context,biz, phone string) error
	Verify(ctx context.Context, biz string, phone string, inputcode string) (bool, error)
}

type IdentifyCodeService struct{
	repo repository.CodeRepository
	smsSvc sms.Service
}

func NewCodeService(repo repository.CodeRepository, smsSvc sms.Service) CodeService {
	return &IdentifyCodeService{
		repo: repo,
		smsSvc: smsSvc,
	}
}

func (svc *IdentifyCodeService) Send(ctx context.Context,biz, phone string) error {
	// 生成一个验证码
	code := svc.generateCode()
	// 塞进Redis
	err:=svc.repo.Store(ctx, biz,phone,code)
	if err!=nil{
		return err
	}
	// 发送出去
	err = svc.smsSvc.Send(ctx,codeTplId, []string{code}, phone)
	return err
}

func (svc *IdentifyCodeService) Verify(ctx context.Context, biz string, phone string,
	inputcode string) (bool, error) {
	return svc.repo.Verify(ctx, biz, phone, inputcode)
}

func (svc *IdentifyCodeService) generateCode() string {
	num:=rand.Intn(1000000)	// 左闭右开
	// 不够6位的，前面加0
	return fmt.Sprintf("%06d", num)
}